# -*- coding: utf-8 -*-
import os,sys
import fnmatch
import time
import re
#import traceback
from .console import clear as console_clear, colors as c_colors
from .console import get_cursor_position, set_cursor_position, \
                     get_text_color, set_text_color, \
                     clear_line_remaining, set_title

log_level = {
    'error': c_colors.FOREGROUND_RED | c_colors.FOREGROUND_INTENSITY,
    'info': c_colors.FOREGROUND_BLUE | c_colors.FOREGROUND_INTENSITY
}
try:
    import win32com.client
    import pythoncom
except:
    pass
def get_disk_queue(path):
    '''
    windows only, need pywin32
    '''    
    try:
        drive = os.path.splitdrive(os.path.realpath(path))[0].upper()
        strComputer = "."
        pythoncom.CoInitialize()
        objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
        objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
        colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfDisk_LogicalDisk")
        for objItem in colItems:
            if objItem.Name != None:
                if objItem.Name.upper() == drive:
                    if objItem.CurrentDiskQueueLength != None:
                        sys.stderr.write("Disk %s QueueLength: %d\n" % (drive, objItem.CurrentDiskQueueLength))
                        return objItem.CurrentDiskQueueLength
    except:
        #traceback.print_exc()
        return 0

def is_locked(filepath):
    """Checks if a file is locked by opening it in append mode.
    If no exception thrown, then the file is not locked.
    """
    locked = None
    file_object = None
    if os.path.exists(filepath):
        try:
            buffer_size = 8
            # Opening file in append mode and read the first 8 characters.
            file_object = open(filepath, 'a', buffer_size)
            if file_object:
                locked = False
        except (IOError, message):
#            print "File is locked (unable to open in append mode). %s." % \
#                  message
            locked = True
        finally:
            if file_object:
                file_object.close()
    else:
        print(("%s not found." % filepath))
    return locked

def wait_for_files(filepaths):
    """Checks if the files are ready.

    For a file to be ready it must exist and can be opened in append
    mode.
    """
    has_locked_file = False
    wait_time = 30
    for filepath in filepaths:
        # If the file doesn't exist, wait wait_time seconds and try again
        # until it's found.
        while not os.path.exists(filepath):
#            print "%s hasn't arrived. Waiting %s seconds." % \
#                  (filepath, wait_time)
            time.sleep(wait_time)
        # If the file exists but locked, wait wait_time seconds and check
        # again until it's no longer locked by another process.
        while is_locked(filepath):
            has_locked_file = True
            write_line_with_sep(sys.stderr, "%s is currently in use. Waiting %s seconds." % \
                  (filepath, wait_time))
            time.sleep(wait_time)
    return has_locked_file

def get_safety_str(str):
    ansi_str = str.encode(sys.getfilesystemencoding(), 'replace')
    safety_str = ansi_str.decode(sys.getfilesystemencoding()).replace('?','_')
    return safety_str
            
class MultiWriter(object):
    def __init__(self, *writes):
        self.writers =  writes
        
    def write(self, text, color=''):       
        for w in self.writers:
            if w.name in ['<stdout>', '<stderr>']:
                # convert the unicode str to system-encoding, when output to console
                if color:
                    old_color = get_text_color()
                    set_text_color(log_level[color])
                w.write(get_safety_str(text))
                if color:
                    set_text_color(old_color)
            else:
                w.write(text)
            w.write(os.linesep)
            w.flush()
    
def write_line_with_sep(file_object, str):    
    file_object.write(get_safety_str(str))
    file_object.write(os.linesep)

def file_filter(filelist, pattern):
    exclude_files = fnmatch.filter(filelist, pattern)
    return [f for f in filelist if not f in exclude_files]

def file_match(filelist, pattern):
    return fnmatch.filter(filelist, pattern)

def file_match_re(filelist, re_pattern):
    reslut = []
    pat = re.compile(re_pattern)
    for file in filelist:
        if pat.match(file):
            reslut.append(file)
    return reslut

def walkDir(dir):
    files = []
    for root,dir,filename in os.walk(dir):
        for f in filename :
            files.append(os.path.join(root,f))
    files.sort()
    return files

def cutstr(source,start,end):
    startpos = source.find(start) + len(start)
    endpos = source.find(end)
    return source[startpos:endpos]

def we_are_frozen():
    """Returns whether we are frozen via py2exe.
    This will affect how we find out where we are located."""

    return hasattr(sys, "frozen")

def module_path(file=''):
    """ This will get us the program's directory,
    even if we are frozen using py2exe"""

    if we_are_frozen():
        return os.path.dirname(sys.executable)
    if not file:
        file = __file__
    return os.path.dirname(file)

def test():
    apath = module_path()
    print(apath)
    files = walkDir(apath)
    print(files)
    
if __name__ == "__main__" :
    test()
    pass
    

